import fs from 'fs'
import schedule from 'node-schedule'
import dayjs from 'dayjs'
let I = {}
export const start = () => {
  fs.readdirSync(__dirname).forEach((n, i) => {
    if (n == 'index.js') return
    let taskName = n.replace(/\.js$/, '')
    let task = require('./' + taskName)

    if(!task.enable) return

    I[taskName] = 0
    let j = schedule.scheduleJob(task.role, async () => {
      if (I[taskName] > 0) return
      console.info('task-run', '---', task.title || taskName, '---', task.role, '---', dayjs().format('YYYY-MM-DD HH:mm:ss'))
      try {
        I[taskName]++
        await task.run()
        I[taskName] = 0
      } catch (error) {
        I[taskName] = 0
        console.error(error)
      }
    })
  })
  console.info('task server started!')
}

export default {
  start
}
